package com.tgy.shiroboot.config;

import com.tgy.shiroboot.entity.User;
import com.tgy.shiroboot.mapper.UserMapper;
import org.apache.catalina.security.SecurityUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;


import javax.annotation.Resource;
import java.util.Objects;


/***
 * @ClassName: UserRealm
 * @Description:
 * @Auther: 送一一块二向箔
 * @Date: 20:34 2022/1/5
 * @version : V1.0
 */

//自定义的Realm
public class UserRealm extends AuthorizingRealm {

    //对日志类的引用
    Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

    @Resource
    UserMapper userMapper;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("执行了=》授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo authInfo = new SimpleAuthorizationInfo();

        //拿到当前登录这个对象
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        if (!Objects.equals(user.getPerms(),null)){
            authInfo.addStringPermission(user.getPerms());
        }
        return authInfo;

    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.info("执行了=》doGetAuthenticationInfo");
        //用户名，密码，数据库中取值

        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        User user = userMapper.getUserByName(userToken.getUsername());
        if (user==null) {
            return null;//抛出异常 UnknownAccountException
        }
        //密码认证shiro做，防止泄露
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
